﻿@using System.ComponentModel.DataAnnotations;
@using System.ComponentModel
@using System.Text.Json;
@inject NotificationService _notice
@inject HttpClient _httpClient
@inject IJSRuntime _JsRuntime
@inject Blazored.LocalStorage.ISyncLocalStorageService _LocalStorage
<Header>
    <div class="logo">猫咪休息站</div>
    <div class="avtM">
        @if (GobalManager.myUsrInfo == null) {
            <Button Ghost OnClick="()=>{_visible=true;}">登录或注册</Button>
        } else {
            <Dropdown Placement="Placement.Bottom" Arrow>
                <Overlay>
                    <Menu OnMenuItemClicked="OnClickAvatar">
                        <MenuItem @key="5" disabled>
                            @GobalManager.myUsrInfo.Name
                        </MenuItem>
                        <MenuDivider />
                        <MenuItem Id="1">
                            <a rel="noopener noreferrer" href="">
                                个人详细信息
                            </a>
                        </MenuItem>
                        <MenuItem Id="2">
                            <a rel="noopener noreferrer" href="" style="color:red">
                                退出登录
                            </a>
                        </MenuItem>
                    </Menu>
                </Overlay>
                <ChildContent>
                    <Avatar Size="large" Src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fblog%2F202111%2F09%2F20211109163907_cb810.thumb.1000_0.jpeg&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1673973800&t=de92108f1a0889f37d6fc565af26c28b" />
                </ChildContent>
            </Dropdown>
        }
    </div>
    <Menu Mode=MenuMode.Horizontal Theme="MenuTheme.Dark">
        <MenuItem Key="home">
            <Icon Type="home" Theme="outline" />
            <MenuLink Href="">主页</MenuLink>
        </MenuItem>
        <MenuItem Key="comment" RouterLink="CatTalk">
            <Icon Type="comment" Theme="outline" />
            猫咪论坛
        </MenuItem>
        <MenuItem Key="alipay" RouterLink="MoreFunc">
            其他功能
        </MenuItem>
    </Menu>
</Header>
<!--登录模块实现-->
@{
    RenderFragment footer = @<Template>
        <Button OnClick="@HandleOk" @key="@( "submit" )"
            Type="primary"
            Loading="@_loading">
            登录
        </Button>
        <Button OnClick="@HandleCancel" @key="@( "back" )">返回</Button>
    </Template>;
}
<Modal Title="@("登录或者注册")"
       Visible="@_visible"
       OnOk="@HandleOk"
       OnCancel="@HandleCancel"
       Footer="@footer"
       MaskStyle="backdrop-filter: blur(3px);background-image: linear-gradient(159deg, #ffcc9769, #00000000);">
    <p>欢迎你，亲爱的猫咪</p>
    <h1>登录</h1>
    <p>输入自己的喵号，以及喵码</p>
    <Form Model="@model"
          OnFinish="OnFinish"
          OnFinishFailed="OnFinishFailed"
          @ref="form">
        <FormItem>
            <Input @bind-Value="@context.Username" />
        </FormItem>
        <FormItem Label="喵码">
            <InputPassword @bind-Value="@context.Password" />
        </FormItem>
        <FormItem WrapperColSpan="16">
            <Checkbox @bind-Value="context.RememberMe">记住本喵 for 30 days</Checkbox>
        </FormItem>
    </Form>
    <p>人喵验证：选择下面是猫咪的照片</p>
    <RadioGroup @bind-Value="radioValue5" ButtonStyle="@RadioButtonStyle.Solid">
        <Radio RadioButton Value="@("A")" Class="RadioClass">
            <img width="130" height="130" src="./Resources/YanZheng/Cat.png" />
        </Radio>
        <Radio RadioButton Value="@("B")" Class="RadioClass">
            <img width="130" height="130" src="./Resources/YanZheng/Dog.png" />
        </Radio>
        <Radio RadioButton Value="@("C")" Class="RadioClass">
            <img width="130" height="130" src="./Resources/YanZheng/CatBird.jpg" />
        </Radio>
    </RadioGroup>
    <h1>注册</h1>
    <p>还没有喵号？点击下方的链接进行注册。</p>
    <a href="/register" target="_blank">注册！成为喵喵休息站的一喵！</a>
    <p>成功后，请刷新页面。</p>
</Modal>

@code {
    //点击头像下拉框
    private void OnClickAvatar(MenuItem e) {
        Console.WriteLine("点击了 " + e.Id);
        switch (e.Id) {
            case "1":
            break;
            case "2":
            GobalManager.myUsrInfo = null;
            _LocalStorage.RemoveItem("unameID");
            break;
        }

    }
    //登录功能的实现
    bool _visible = false;
    bool _loading = false;
    string radioValue5 = "A";//人喵验证号码
    public class Model {
        [Required, DisplayName("喵号")]
        public string Username { get; set; }
        [Required]
        public string Password { get; set; }
        public bool RememberMe { get; set; } = true;
    }
    private Form<Model> form;
    private Model model = new Model();
    private LoginData loginData = new LoginData();

    private async Task HandleOk(MouseEventArgs e) {
        _loading = true;
        form.Submit();
        _visible = true;
    }

    private void HandleCancel(MouseEventArgs e) {
        _visible = false;
        _httpClient.PostAsync(GobalManager.serverURL + "/UsrLogin", new FormUrlEncodedContent(new List<KeyValuePair<string, string>>()                                                  {new KeyValuePair<string, string>("name","小明"),new KeyValuePair<string,string>("age","20")
        }));
    }
    //通知类的实现
    private async Task NoticeWithIcon(NotificationType type, string msg, string title = "通知") {
        await _notice.Open(new NotificationConfig() {
                Message = title,
                Description = msg,
                NotificationType = type
            });
    }
    async void LoginMain() {
        try {
            loginData.usrPwd = model.Password;
            loginData.usrID = model.Username;
            loginData.remberMe = model.RememberMe;
            using var response = await _httpClient.PostAsJsonAsync(GobalManager.serverURL + "/UsrLogin", loginData);
            _loading = false;
            if (response.StatusCode == System.Net.HttpStatusCode.Locked) {
                //登录失败
                NoticeWithIcon(NotificationType.Error, "失败！检查账号或密码是否正确！");
            } else if (response.StatusCode == System.Net.HttpStatusCode.OK) {
                //登录成功
                _visible = false;
                NoticeWithIcon(NotificationType.Success, "登录成功");

                Console.WriteLine("响应消息：" + response.Content);
                var data = await response.Content.ReadFromJsonAsync<UsrInfo>();
                Console.WriteLine("接受到的登录消息：" + data?.Name + " " + data?.Description);
                GobalManager.myUsrInfo = data;
                //保存用户信息
                if (model.RememberMe == false) {
                    Console.WriteLine("用户不保存Cookie");
                    //await _JsRuntime.InvokeVoidAsync("displayDate");
                    _LocalStorage.RemoveItem("unameID");
                } else {
                    _LocalStorage.SetItem("unameID", GobalManager.myUsrInfo?.ID);
                }
            } else {
                //未知错误
                NoticeWithIcon(NotificationType.Error, "未知的错误。可能后端服务器没有打开。");
            }
            GobalManager.dCatTalkBody?.Invoke();
            StateHasChanged();
        }
        catch (Exception ex) {
            Console.WriteLine("登录异常" + ex.Message);
            await NoticeWithIcon(NotificationType.Error, "错误。可能后端服务器没有打开。" + ex.Message); 
            _loading = false;
        }
    }
    private void OnFinish(EditContext editContext) {
        Console.WriteLine($"Success:{JsonSerializer.Serialize(model)}");
        if (radioValue5.Equals("A")) {
            this.LoginMain();
        } else {
            _loading = false;
            NoticeWithIcon(NotificationType.Error, "验证码校验失败！");
        }
    }

    private void OnFinishFailed(EditContext editContext) {
        _visible = false;
        _loading = false;
        Console.WriteLine($"Failed:{JsonSerializer.Serialize(model)}");
    }

    public void SetValued() {
        Console.WriteLine("CusNav组件已经被刷新");
        GobalManager.dCatTalkBody?.Invoke();
        StateHasChanged();
    }

    protected override void OnInitialized() {
        //注册委托
        GobalManager.dCusNVCD += new GobalManager.OnStatementChanged(this.SetValued);
        base.OnInitialized();
    }
}

<style>
    .site-layout-content {
        background: #fff;
        padding: 24px;
        min-height: 280px;
    }

    .logo {
        width: auto;
        height: 31px;
        float: left;
        letter-spacing: 5px;
        color: white;
        margin-right: 30px;
    }

    .avtM {
        width: 100px;
        float: right;
        text-align: right;
    }

    .RadioClass {
        padding: 0;
        margin: 0;
        height: min-content;
        width: min-content;
        padding: 5px;
    }
</style>
